#include "LoginController.h"
#include <QMessageBox>

LoginController::LoginController(LoginUI *ui, NetworkManager *network, QObject *parent) :
    QObject(parent), m_ui(ui), m_network(network),
    m_isRegisterMode(false), m_loginStage(CheckAccount), m_regStage(CheckRegUsername)
{
    // 关联UI信号
    connect(m_ui->loginButton(), &QPushButton::clicked, this, &LoginController::onLoginButtonClicked);
    connect(m_ui->registerButton(), &QPushButton::clicked, this, &LoginController::onRegisterButtonClicked);
    connect(m_ui->closeButton(), &QPushButton::clicked, this, &LoginController::onCloseButtonClicked);

    // 关联网络信号
    connect(m_network, &NetworkManager::tlvReceived, this, &LoginController::onServerReply);
    connect(m_network, &NetworkManager::errorOccurred, this, &LoginController::onNetworkError);

    connect(m_network, &NetworkManager::connected, this, []() {
            qDebug() << "服务器连接成功";
        });
    // 初始连接服务器
    m_network->connectToServer();
}

void LoginController::onLoginButtonClicked()
{
    if (m_isRegisterMode) {
        // 注册模式下点击登录按钮：切换到登录模式
        m_isRegisterMode = false;
        m_ui->setLoginMode(true);
        resetState();
    } else {
        // 登录模式下点击登录按钮：提交登录
        handleLoginSubmit();
    }
}

void LoginController::onRegisterButtonClicked()
{
    if (m_isRegisterMode) {
        // 注册模式下点击：提交注册
        handleRegSubmit();
    } else {
        // 登录模式下点击：切换到注册模式
        m_isRegisterMode = true;
        m_ui->setLoginMode(false);
        resetState();
    }
}

void LoginController::onCloseButtonClicked()
{
    m_ui->parentWidget()->close();
}

void LoginController::onServerReply(const wd::TLV &tlv)
{
    qDebug() << "收到服务器回复：type=" << tlv.type << ", length=" << tlv.length
                 << ", data=" << QString::fromUtf8(tlv.data, tlv.length);
    if (m_isRegisterMode) {
        qDebug()<<"张衡是狗"<<endl;
        handleRegReply(tlv);

    } else {
        qDebug()<<"张衡是猪"<<endl;
        handleLoginReply(tlv);

    }
}

void LoginController::onNetworkError(const QString &error)
{
    QMessageBox::warning(m_ui, "网络错误", error);
    resetState();
}

void LoginController::handleLoginSubmit()
{
    QString username = m_ui->getUsername();
    QString password = m_ui->getPassword();

    // 本地验证
    if (username.isEmpty() || password.isEmpty()) {
        QMessageBox::warning(m_ui, "输入错误", "账号和密码不能为空");
        return;
    }

    // 检查连接状态
//    if (!m_network->isConnected()) {
//        QMessageBox::warning(m_ui, "连接失败", "未连接到服务器，请检查网络");
//        m_network->connectToServer();
//        return;
//    }
    if (!m_network->isConnected()) {
          QMessageBox::information(m_ui, "提示", "正在连接服务器，请稍候...");
          // 连接成功后自动重试登录
          auto retryLogin = [this]() {
              handleLoginSubmit();
              // 避免重复触发，断开临时连接
              disconnect(m_network, &NetworkManager::connected, this, nullptr);
          };
          connect(m_network, &NetworkManager::connected, this, retryLogin, Qt::UniqueConnection);
          m_network->connectToServer();  // 发起连接
          return;
      }
    // 保存当前信息，进入登录第一阶段
    m_currentUser = username;
    m_tempPwd = password;
    m_loginStage = CheckAccount;

    // 构建TLV数据包（登录第一阶段）
    wd::TLV tlv;
    tlv.type = wd::TASK_TYPE_LOGIN_SECTION1;
    QByteArray userData = username.toUtf8();
    int len = qMin(userData.size(), 1023);
    memcpy(tlv.data, userData.constData(), len);
    tlv.data[len] = '\0';
    tlv.length = len;

    // 发送数据并更新UI状态
    m_network->sendTlvPacket(tlv);
    m_ui->setButtonsEnabled(false);
    m_ui->setLoginButtonText("验证账号中...");
}

void LoginController::handleLoginReply(const wd::TLV &tlv)
{

    if (m_loginStage == CheckAccount) {
        // 处理登录第一阶段回复
        m_ui->setLoginButtonText("登录");
        m_ui->setButtonsEnabled(true);

        if (tlv.type == wd::TASK_TYPE_LOGIN_SECTION1_RESP_OK) {
            // 用户名存在，获取盐值
            m_salt = QString::fromUtf8(tlv.data, tlv.length);
            qDebug()<<"盐值为:"<<m_salt<<endl;
            m_loginStage = SendPassword;
            sendEncryptedPassword();  // 发送加密密码
        } else if (tlv.type == wd::TASK_TYPE_LOGIN_SECTION1_RESP_ERROR) {
            // 用户名错误
            QString errorMsg = QString::fromUtf8(tlv.data, tlv.length);
            QMessageBox::warning(m_ui, "登录失败", errorMsg);
        } else {
            QMessageBox::warning(m_ui, "错误", "未知的服务器响应类型");
        }
    } else if (m_loginStage == SendPassword) {
        // 处理登录第二阶段回复
        m_ui->setLoginButtonText("登录");
        m_ui->setButtonsEnabled(true);

        if (tlv.type == wd::TASK_TYPE_LOGIN_SECTION2_RESP_OK) {
            // 登录成功
            QMessageBox::information(m_ui, "成功", "登录成功");
            emit loginSuccess();
        } else if (tlv.type == wd::TASK_TYPE_LOGIN_SECTION2_RESP_ERROR) {
            // 密码错误
            QString errorMsg = QString::fromUtf8(tlv.data, tlv.length);
            QMessageBox::warning(m_ui, "登录失败", errorMsg);
            m_ui->clearInputs();
        } else {
            QMessageBox::warning(m_ui, "错误", "未知的服务器响应类型");
        }
    }
}

void LoginController::sendEncryptedPassword()
{
    // 使用服务器返回的盐值加密密码
    QString encryptedPassword = encryptPassword(m_tempPwd, m_salt);

    // 构建TLV数据包
    wd::TLV tlv;
    tlv.type = wd::TASK_TYPE_LOGIN_SECTION2;
    QByteArray data = encryptedPassword.toUtf8();
    int len = qMin(data.size(), 1023);
    memcpy(tlv.data, data.constData(), len);
    tlv.data[len] = '\0';
    tlv.length = len;

    // 发送数据并更新UI
    m_network->sendTlvPacket(tlv);
    m_ui->setButtonsEnabled(false);
    m_ui->setLoginButtonText("验证密码中...");
}

void LoginController::handleRegSubmit()
{
    QString username = m_ui->getUsername();
    QString password = m_ui->getPassword();
    QString confirmPwd = m_ui->getConfirmPassword();

    // 本地验证
    if (username.isEmpty() || password.isEmpty() || confirmPwd.isEmpty()) {
        QMessageBox::warning(m_ui, "输入错误", "所有字段不能为空");
        return;
    }
    if (password != confirmPwd) {
        QMessageBox::warning(m_ui, "输入错误", "两次密码输入不一致");
        return;
    }
    if (password.length() < 6) {
        QMessageBox::warning(m_ui, "输入错误", "密码长度不能少于6位");
        return;
    }

    // 检查连接状态
//    if (!m_network->isConnected()) {
//        QMessageBox::warning(m_ui, "连接失败", "未连接到服务器，请检查网络");
//        m_network->connectToServer();
//        return;
//    }

    if (!m_network->isConnected()) {
           QMessageBox::information(m_ui, "提示", "正在连接服务器，请稍候...");
           auto retryReg = [this]() {
               handleRegSubmit();
               disconnect(m_network, &NetworkManager::connected, this, nullptr);
           };
           connect(m_network, &NetworkManager::connected, this, retryReg, Qt::UniqueConnection);
           m_network->connectToServer();
           return;
       }
    // 保存注册信息，进入注册第一阶段
    m_currentUser = username;
    m_tempPwd = password;
    m_regStage = CheckRegUsername;

    // 构建TLV数据包（注册第一阶段）
    wd::TLV tlv;
    tlv.type = wd::TASK_TYPE_REGISTER1;
    QByteArray userData = username.toUtf8();
    int len = qMin(userData.size(), 1023);
    memcpy(tlv.data, userData.constData(), len);
    tlv.data[len] = '\0';
    tlv.length = len;

    // 发送数据并更新UI
    m_network->sendTlvPacket(tlv);
    m_ui->setButtonsEnabled(false);
    m_ui->setRegisterButtonText("检查用户名中...");
}

void LoginController::handleRegReply(const wd::TLV &tlv)
{
    if (m_regStage == CheckRegUsername) {
        // 处理注册第一阶段回复
        m_ui->setButtonsEnabled(true);
        m_ui->setRegisterButtonText("提交注册");

        if (tlv.type == wd::TASK_TYPE_REGISTER1_RESP_OK) {
            // 用户名可用，获取服务器盐值
            m_salt = QString::fromUtf8(tlv.data, tlv.length);
            qDebug()<<"盐值为："<<m_salt;
            // 加密密码并发送
            QString encryptedPwd = encryptPassword(m_tempPwd, m_salt);
            qDebug()<<"加密后的密码为:"<<encryptedPwd;
            if(m_salt==NULL)
            {
                qDebug()<<"我真帅"<<endl;
            }
            wd::TLV regTlv;
            regTlv.type = wd::TASK_TYPE_REGISTER2;
            QByteArray data = encryptedPwd.toUtf8();
            int len = qMin(data.size(), 1023);
            memcpy(regTlv.data, data.constData(), len);
            regTlv.data[len] = '\0';
            regTlv.length = len;

            m_network->sendTlvPacket(regTlv);
            m_regStage = SubmitRegData;
            m_ui->setButtonsEnabled(false);
            m_ui->setRegisterButtonText("注册中...");
        } else if (tlv.type == wd::TASK_TYPE_REGISTER1_RESP_ERROR) {
            // 用户名不可用
            QString errorMsg = QString::fromUtf8(tlv.data, tlv.length);
            QMessageBox::warning(m_ui, "注册失败", errorMsg);
        } else {
            QMessageBox::warning(m_ui, "错误", "未知的注册响应类型");
        }
    } else if (m_regStage == SubmitRegData) {
        // 处理注册结果
        m_ui->setButtonsEnabled(true);
        m_ui->setRegisterButtonText("提交注册");

        if (tlv.type == wd::TASK_TYPE_REGISTER2_RESP_OK) {
            // 注册成功，切换到登录模式
            QMessageBox::information(m_ui, "注册成功", "账号注册成功，请登录");
            m_isRegisterMode = false;
            m_ui->setLoginMode(true);
        } else if (tlv.type == wd::TASK_TYPE_REGISTER2_RESP_ERROR) {
            // 注册失败
            QString errorMsg = QString::fromUtf8(tlv.data, tlv.length);
            QMessageBox::warning(m_ui, "注册失败", errorMsg);
        } else {
            QMessageBox::warning(m_ui, "错误", "未知的注册响应类型");
        }
    }
}

QString LoginController::encryptPassword(const QString &password, const QString &salt)
{
    QCryptographicHash hash(QCryptographicHash::Sha256);
    hash.addData(salt.toUtf8());
    hash.addData(password.toUtf8());
    return QString(hash.result().toHex());
}

void LoginController::resetState()
{
    if (m_isRegisterMode) {
        m_ui->setRegisterButtonText("提交注册");
    } else {
        m_ui->setLoginButtonText("登录");
    }
    m_ui->setButtonsEnabled(true);
}
